#! /usr/bin/env python3
import pymysql
import re
import sys

try:
    sys.stdout = open('/tmp/accounts.pp','w')
    print("class localaccounts::accounts {")
    #conn=MySQLdb.connect(host='ccs.ihep.ac.cn',user='puppet',passwd='puppet;123',db='cluster',port=3306,cursorclass = MySQLdb.cursors.DictCursor)
    conn=pymysql.connect(host='ccs.ihep.ac.cn',user='puppet',passwd='puppet;123',db='cluster',port=3306)
    cur=conn.cursor()
    cur.execute('select a.afsaccount,a.fullaccount,b.group2value,a.afsgroup22,a.homedirectory,a.afstype2,a.uid,a.islock,a.del_flag from afsuser as a,afsgroup2 as b where a.afsgroup2=b.group2id')
    #cur.execute('select a.afsaccount,a.fullaccount,b.group2value,a.afsgroup22,a.homedirectory,a.afstype2,a.uid from afsuser as a,afsgroup2 as b where a.afsgroup2=b.group2id and a.afsaccount!="fengf"')
    users=cur.fetchall()
    cur.execute("select group2id,group2name from afsgroup2 where islock='0'")
    groups=cur.fetchall()
    cur.execute("select group2value,group2name from afsgroup2 where islock='0'")
    groupid=cur.fetchall()
    pgroups=dict(groups)
    dgroupid=dict(groupid)
    # change a.homedirectory to system homedir
    for r in users:
      if r[6]<100000:
        if re.search(r'/afs',r[4],re.M|re.I):
          uhome=r[4]+"/"+r[0][0]+"/"+r[0]
        else:
          uhome=r[4]+"/"+r[0]
        #print uhome
        #print r
        # Get group list form a.afsgroup22

        ugrouplist = []
        if r[3].strip()!='':
          ugroups = r[3].split(",")
          for a in ugroups:
            ugrouplist.append(pgroups.get(int(a)))
        if len(ugrouplist):
          #print ugrouplist
          #print dgroupid.get(r[2])
          try:
            ugrouplist.remove(dgroupid.get(r[2]))
          except:
            pass
          #print ugrouplist
        print("  user { '" + r[0] + "':")
        # if user id delete then set to delete
        if r[8] == '1':
          print("    ensure      => 'absent',")
        else:
          print("    ensure      => 'present',")
          print("    comment     => '" + r[1] + "',")
          print("    gid         => '" + r[2] + "',")
          print("    home        => '" + uhome + "',")
          # if user is locked then set shell to nologin
          if r[7] == '1':
            print("    shell       => '/sbin/nologin',")
          else:
            print("    shell       => '/bin/" + r[5] + "',")
          print("    uid         => '" + str(r[6]) + "',")
          print("    membership  => inclusive,")
          #if ugrouplist:
          print("    groups      => " + str(ugrouplist) + ",")
        print("  }")
    for r in groupid:
      print("  group { '" + r[1] + "':")
      print("    ensure     => 'present',")
      print("    allowdupe  => true,")
      print("    gid     => '" + r[0] + "',")
      print("  }")
    print("}")
    cur.close()
    conn.close()
    sys.stdout.close()
except:
    print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit(1)
